package com.lagou;

import com.lagou.rpc.netty.RpcServerBootStrap;
import com.lagou.rpc.regist.RpcRegister;
import com.lagou.util.GetIP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.util.concurrent.CountDownLatch;

/**
 * @ClassName RpcServerApplication
 * @Description
 * @Author playboy
 * @Date 2021/6/5 3:14 下午
 * @Version 1.0
 **/
@SpringBootApplication
public class RpcServerApplication implements CommandLineRunner, EnvironmentAware {

	public static void main(String[] args) {
		SpringApplication.run(RpcServerApplication.class, args);
	}

	@Autowired
	private RpcServerBootStrap rpcServerBootStrap;

	@Autowired
	private RpcRegister rpcRegister;

	Environment environment;

	@Override
	public void run(String... args) throws Exception {
		//启动netty的服务端，提供远程rpc的服务
		CountDownLatch countDownLatch = new CountDownLatch(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				rpcServerBootStrap.rpcStart(countDownLatch);
			}
		}).start();
		//自动注册ip和port到zookeeper
		countDownLatch.await();
		String port = environment.getProperty("spring.rpc.port");
		String hostAddress = GetIP.getLocalAddress().getHostAddress();
		rpcRegister.register(hostAddress + ":" + port);
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}
